package com.alinesno.cloud.initializr.starter.git.job;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;
import com.alinesno.cloud.initializr.starter.entity.BuildGitEntity;
import com.alinesno.cloud.initializr.starter.enums.GitRepositoryEnum;
import com.alinesno.cloud.initializr.starter.git.utils.AccessTokenUtils;
import com.alinesno.cloud.initializr.starter.service.IBuildGitService;

/**
 * 定时刷新accessToken
 * @author WeiXiaoJin
 * @since 2022年3月11日 下午10:45:43
 */
@EnableScheduling
@Component
public class RefreshAccessToken {

	@Autowired
	private IBuildGitService buildGitService ; 
	
	@Autowired
	private AccessTokenUtils tokenUtil ; 
	
	/**
	 * 刷新token，每两个小时刷新一次
	 */
//	@Scheduled(cron = "*/15 * * * * ?")
	@Scheduled(cron = "0 0 */2 * * ?")
	public void refreshToken() {
		
		List<BuildGitEntity> list = buildGitService.findAll() ; 
	
		for(BuildGitEntity e : list) {
			
			if(e.getRefreshToken() == null) {
				continue ; 
			}
			
			JSONObject accessToken  = null ; 
			
			if(GitRepositoryEnum.GITEE.getName().equals(e.getGitType())) {
				accessToken = tokenUtil.refreshGiteeToken(e) ; 
				
				if(accessToken != null) {
					
					e.setAccessPrivateToken(accessToken.getString("access_token"));
					e.setRefreshToken(accessToken.getString("refresh_token"));
					e.setExpiresIn(accessToken.getIntValue("expires_in"));
					
					buildGitService.update(e) ;
					
				}
			} else if(GitRepositoryEnum.GITEA.getName().equals(e.getGitType())) {
				if(e.getInnerGit() == 1) {  // 内置的gitea配置
					accessToken =  tokenUtil.refreshGiteaToken(e) ; 
				}else {
					accessToken = tokenUtil.refreshGiteaSelfToken(e) ; 
				}
				
				if(accessToken != null) {
					e.setAccessPrivateToken(accessToken.getString("access_token"));
					e.setRefreshToken(accessToken.getString("refresh_token"));
					e.setExpiresIn(accessToken.getIntValue("expires_in"));
					
					buildGitService.update(e) ;
				}
			}
		}
		
	}
	
}
